package leetcode_链表;

import java.util.HashMap;
import java.util.Map;

/**
 * 随机链表的复制
 * 算法：哈希表、链表
 *
 * @author yezh
 * @date 2024/1/11 14:20
 */
public class _138 {

    public Node copyRandomList_imporve(Node head) {
        if (head == null) return head;
        Node cur = head, next;
        while (cur != null) {
            next = cur.next;
            cur.next = new Node(cur.val);
            cur.next.next = next;
            cur = next;
        }
        cur = head;
        while (cur != null) {
            next = cur.next.next;
            if (cur.random != null) cur.next.random = cur.random.next;
            cur = next;
        }
        Node dummy = new Node(-1);
        cur = dummy;
        while (head != null) {
            next = head.next.next;
            cur.next = head.next;
            head.next = next;
            head = next;
            cur = cur.next;
        }
        return dummy.next;
    }

    public Node copyRandomList(Node head) {
        if (head == null) return null;
        Map<Node, Node> map = new HashMap<>();
        Node cur = head;
        while (cur != null) {
            Node node = new Node(cur.val);
            map.put(cur, node);
            cur = cur.next;
        }
        map.forEach((oldNode, newNode) -> {
            if (oldNode.next != null) newNode.next = map.get(oldNode.next);
            if (oldNode.random != null) newNode.random = map.get(oldNode.random);
        });
        return map.get(head);
    }

    static class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

}
